'use strict';

const jwt = require('jsonwebtoken');

module.exports = (options, app) => {
  return async function userInterceptor(ctx, next) {
    let authToken = ctx.headers.authorization;
    if (authToken) {
      authToken = authToken.substring(7);
      const result = verifyToken(authToken, options.secret);
      if (!result) {
        ctx.body = { code: 401, msg: 'token过期请重新登录!' };
        return;
      }
      await next();
    } else {
      ctx.body = { code: 402, msg: '请登陆后再进行操作' };
    }
  };
};

function verifyToken(token, secret) {
  let str = {
    iat: 1,
    exp: 0,
    msg: '',
  };
  const decode = jwt.verify(token, secret, (err, decode) => {
    if (err) {
      switch (err.name) {
        case 'TokenExpiredError':
          str.msg = 'token 过期';
          return str;
        case 'JsonWebTokenError':
          str.msg = 'token 失效';
          return str;
        default:
          str.msg = '发生错误';
          return str;
      }
    } else {
      return decode;
    }
  });
  const { exp } = decode,
    current = Math.floor(Date.now() / 1000);
  /* 对exp进行校验 默认是一个小时 */
  return current <= exp;
}
